package com.example.springboot.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.example.springboot.controller.dto.LoginDto;
import com.example.springboot.controller.request.LoginRequest;
import com.example.springboot.entity.User;
import com.example.springboot.exception.ServiceException;
import com.example.springboot.mapper.UserMapper;
import com.example.springboot.controller.request.UserPageRequset;
import com.example.springboot.service.IUserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service//表明将此类注入spring容器，为@Autowired使用
public class UserService implements IUserService {

    @Autowired
    UserMapper userMapper;

    private static final String DEFAULT_PASS = "123";//默认密码
    private static final String PASS_SALT = "yozr";//salt

    @Override//获取所有用户信息
    public List<User> list() {
        return userMapper.list();
    }

    @Override//获取分页用户信息,利用插件实现
    public PageInfo<User> page(UserPageRequset userPageRequset){
        PageHelper.startPage(userPageRequset.getPageNum(), userPageRequset.getPageSize());
        List<User> users = userMapper.listByCondition(userPageRequset);
        return new PageInfo<>(users);
    }

    @Override//添加新用户
    public void save(User user) {
        user.setCreatetime(new Date());
        Date date = new Date();
        //当作卡号处理,随机生成卡号，形式为日期+随机正数
        user.setUsername(DateUtil.format(date, "yyyyMMdd") + Math.abs(IdUtil.fastSimpleUUID().hashCode()));//取绝对值，避免出现负号
        user.setRole("0");
        user.setStatus(true);
        //默认密码 123
        user.setPassword(securePass(user.getPassword()));  // 设置md5加密，加盐
        try {
            userMapper.save(user);
        } catch (DuplicateKeyException e) {
            log.error("数据插入失败， username:{}", user.getUsername(), e);
            throw new ServiceException("用户名重复");
        }
//        userMapper.save(user);
    }

    @Override
    public User getById(Integer id) {
        return userMapper.getById(id);
    }

    @Override
    public void updateById(User user) {
        user.setUpdatetime(new Date());
        userMapper.updateById(user);
    }

    @Override
    public void deleteById(Integer id) {
        userMapper.deleteById(id);
    }

    @Override
    public void handleAccount(User user) {
        Integer score = user.getScore();
        if (score == null) {
            return;
        }
        Integer id = user.getId();
        User dbUser = userMapper.getById(id);
        dbUser.setAccount(dbUser.getAccount() + score);
        userMapper.updateById(dbUser);
    }

    //登录业务
    @Override
    public LoginDto login(LoginRequest request) {
        User user = null;
        try {
            user = userMapper.getByUsername(request.getUsername());//查出的username必须唯一才可
//            System.out.println(user);
        } catch (Exception e) {
            log.error("根据用户名{} 查询出错", request.getUsername());
            throw new ServiceException("用户名错误");
        }
        if (user == null) {
            throw new ServiceException("用户名或密码错误");
        }
        // 判断密码是否合法
        String securePass = securePass(request.getPassword());
        if (!securePass.equals(user.getPassword())) {
            throw new ServiceException("用户名或密码错误");
        }

        if (!user.isStatus()) {
            throw new ServiceException("当前用户处于禁用状态，请联系管理员");
        }

        LoginDto loginDto = new LoginDto();
        BeanUtils.copyProperties(user, loginDto);//把user数据赋给logindto

        // 生成token
//        String token = UserTokenUtils.genToken(String.valueOf(admin.getId()), admin.getPassword());//为数据安全进行token验证
//        loginDto.setToken(token);
        loginDto.setToken("user");//将全局token设为"user"---有问题
        return loginDto;
    }

    private String securePass(String password) {//设置加密密码，加盐
        return SecureUtil.md5(password + PASS_SALT);
    }
}
